/*
 * Copyright (C) 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Called when gadget state is changed.
 */
function onChange() {
  var waveState = wave.getState();
  if (waveState == null) {
    return;
  }
  wave.log('Gadget state is ' + waveState);
  
  // Default value of r121 just for demo-ing
  var buildId = waveState.get('buildId', 'r121');
  if (wave.getMode() == wave.Mode.EDIT) {
    if ($('#buildId > input').size() == 0) {
      $('#buildId').empty();
    }
    $('#buildId').html('<input type="text" />');
    $('#buildId > input').val(gadgets.util.escapeString(buildId));
  } else {
    if ($('#buildId > input').size() != 0) {
      // If was editing, grab the value that was there.
      wave.getState().submitValue('buildId', $('#buildId > input').val());
    }
    $('#buildId').html(gadgets.util.escapeString(buildId))
  }
  
  var status = waveState.get('status', 'Testing');
  $('#status').html(gadgets.util.escapeString(status))

  gadgets.window.adjustHeight();
}

/**
 * Gadget initialisation function.
 */
function init() {
  wave.setStateCallback(onChange);
  wave.setModeCallback(onChange);
  
  $('#buildId > input').live('blur', function(event) {
    wave.getState().submitValue('buildId', $(event.target).val());
  });
}


gadgets.util.registerOnLoadHandler(init);
